#!/usr/bin/env python  
# encoding: utf-8   

""" 
@version: v1.0 
@author: null 
@software: PyCharm 
@file: auth.py 
@time: 2017.4.29 9:25 
"""

from weibo.url import URL
import weibo.settings as config
import requests
import simplejson as json

import sqlite3

def need_login(func):
    """
    用户认证装饰器(判断用户是否已经登录)
    """

    def wrapper(self, *args, **kwargs):

        success = True
        cookies = getCookie(self.username)
        proxy = self.proxy or {}
        if not cookies:
            success = False
        elif cookies["cookie"]=="" or cookies["st"]=="" or cookies["json"]=="":
            success = False
        else:
            print('test_index')
            session = requests.session()
            config.headers["Cookie"]=cookies["cookie"]
            mblog = session.get(url=URL.myblogs(), headers=config.headers,proxies=proxy)
            try:
                data = mblog.json()
                self.session = session
                self.st = cookies["st"]
                self.jsonobj =json.loads(cookies["json"])
                cookie = {}
                ckarray = cookies["cookie"].split(";")
                for i in range(0,len(ckarray)-1):
                    v = ckarray[i].split("=")
                    cookie[v[0].strip()]=v[1].strip()
                ck = requests.utils.cookiejar_from_dict(cookie, cookiejar=None, overwrite=True)
                self.session.cookies= ck
                print("使用cookie缓存")
            except Exception as e:
                print(e)
                success = False
                print("cookie失效，尝试重新登录")
            pass

        if not success:
            username = self.username
            password = self.password
            success = self.login(username, password,proxy)
            while not success:
                username = input("输入用户名:")
                password = input("输入密码:")
                success = self.login(username, password,proxy)
        if success:
            result = func(self,*args, **kwargs)
            return result

    return wrapper


def getCookie(username):

    conn = sqlite3.connect('..\weibo\db\weiboInfo.db')
    select_tb="select * from userInfo WHERE username='%s'"%(username)

    try:
        cursor = conn.execute(select_tb)
        data = cursor.fetchall()
        conn.close()
        cookies={"cookie":data[0][2],"st":data[0][3],"json":data[0][4]}
        return cookies
    except:
        print("数据库查询cookie失败")
        conn.close()
        return False

    pass
